package jespeak.dict;

import java.util.ArrayList;
import java.util.StringTokenizer;

public class DictRule {
	private boolean hasConditional;
	private boolean conditional;
	private int voiceNumber;

	private String word;
	private String phoneme;
	private ArrayList<String> flags;

	private String removeCondition(String s) {
		StringTokenizer st = new StringTokenizer(s);
		String str = st.nextToken();
		s = s.substring(str.length());
		return s;
	}

	public ArrayList<String> getFlags() {
		return flags;
	}

	private boolean isCombination(String line) {
		if (line.startsWith("(")) {
			int ends = line.lastIndexOf(")");
			String combinedWord = line.substring(1, ends);
			System.out.println("Found combined " + combinedWord);
			return true;
		}
		return false;
	}



	public DictRule(String line) {
		hasConditional = false;
		phoneme = null;
		line = line.trim();
		StringTokenizer st;
		String currentToken;
		if (line.startsWith("?!")) {
			hasConditional = true;
			conditional = false;
			st = new StringTokenizer(line);
			currentToken = st.nextToken();
			voiceNumber = Integer.parseInt(currentToken.substring(2));
			line = removeCondition(line);
		}
		else if (line.startsWith("?")) {
			hasConditional = true;
			conditional = true;
			st = new StringTokenizer(line);
			currentToken = st.nextToken();
			voiceNumber = Integer.parseInt(currentToken.substring(1));
			line = removeCondition(line);
		}
		st = new StringTokenizer(line);
		currentToken = st.nextToken();
		if (line.startsWith("(")) {
			int end = line.indexOf(")");
			word = line.substring(1, end);
//			System.out.println("Found combined " + word);
			while (currentToken.endsWith(")") == false)
				currentToken = st.nextToken();
			currentToken = st.nextToken();
//			System.out.println("Found combined " + word + " " + currentToken);
		}
		else {
			word = currentToken; // check if two words to remove (...)
			currentToken = st.nextToken();
		}
		if (currentToken.startsWith("$") == false) {
			phoneme = currentToken;
		}
		else {
			// phoneme is missing
			phoneme = null;
		}
		if (st.hasMoreTokens())
			flags = new ArrayList<String>();
		while (st.hasMoreTokens()) {
			currentToken = st.nextToken();
			flags.add(currentToken);
		}
	}

	public String getPhoneme() {
		return phoneme;
		// todo: do something with flags???
	}

	public String getWord() {
		return word;
	}
}